package com.youku.api;

import java.util.Arrays;
import java.util.Random;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.youku.exception.AssertException;
import com.youku.util.EncryptHelper;

public class Invoker {

	private final Logger logger = LoggerFactory.getLogger(Invoker.class);

	private static final Random random = new Random();

	private String invokeFormatter;

	public Invoker(String invokeFormatter) {
		this.invokeFormatter = invokeFormatter;
	}

	public void print(Object o) {
		System.out.println("out=>" + o);
	}

	public void assertTrue(Object result) {
		logger.debug("验证表达式{}", invokeFormatter);
		boolean r = (boolean) result;
		if (!r) {
			throw new AssertException("验证表达式" + invokeFormatter + "执行不通过");
		}
	}
	
	public String uuid() {
		return UUID.randomUUID().toString();
	}

	public int random(Object n) {
		if (n == null) {
			throw new IllegalArgumentException("方法" + invokeFormatter + "执行错误，参数不能为空");
		}

		try {
			return random.nextInt(Integer.parseInt(n.toString()));
		} catch (NumberFormatException e) {
			throw new IllegalArgumentException("方法" + invokeFormatter + "执行错误，参数不是数字类型");
		}
	}

	public String md5(Object obj) {
		if (obj == null) {
			throw new IllegalArgumentException("md5加密的不能为空");
		}
		return EncryptHelper.md5(obj.toString());
	}

	public boolean strContains(Object text, Object contains) {
		if (text == null || contains == null)
			return false;
		String t = (String) text;
		String c = (String) contains;

		return t.contains(c);
	}

	public String join(Object... objs) {
		if (objs == null) {
			throw new IllegalArgumentException("参数不能为空");
		}

		StringBuilder builder = new StringBuilder();
		for (Object obj : objs) {
			if (obj == null) {
				throw new IllegalArgumentException("参数列表" + Arrays.toString(objs) + "存在空元素");
			} else {
				builder.append(obj);
			}
		}

		return builder.toString();
	}

}
